using System.Diagnostics;
using System.Drawing;
using mebc2.reflection;

namespace mebc2.viewer
{
    public static class DotViewer
    {
        public static void ShowGraph(this MetaData metadata)
        {
            ShowDot(metadata.ToDot());
        }


        public static Image CompileGraphToImage(string dotSource)
        {
            var pDotInfo = new ProcessStartInfo(@"C:\Program Files\Graphviz2.20\bin\dot", "-Tpng")
                               {
                                   CreateNoWindow = true,
                                   WindowStyle = ProcessWindowStyle.Hidden,
                                   UseShellExecute = false,
                                   RedirectStandardInput = true,
                                   RedirectStandardOutput = true
                               };

            var pDot = new Process {StartInfo = pDotInfo};
            pDot.Start();

            pDot.StandardInput.Write(dotSource);
            pDot.StandardInput.Flush();
            pDot.StandardInput.Close();

            var img = Image.FromStream(pDot.StandardOutput.BaseStream);
            pDot.StandardOutput.Close();

            pDot.WaitForExit();

            return img;
        }


        public static void ShowDot(string dotSource)
        {
            var dotImg = CompileGraphToImage(dotSource);
            ShowImage(dotImg);
        }


        public static void ShowImage(Image img)
        {
            var v = new DotView(img);
            v.ShowDialog();
        }
    }
}